//
//  PhoneBindNewView.swift
//  KoiAccounting
//
//  绑定一个新手机号
//  Created by 纪洪文 on 22.04.25.
//

import SwiftUI

struct PhoneBindNewView: View {
    private let maxPhoneLenght = 13
    @Environment(\.presentationMode) var presentationMode;
    @Environment(\.presentToast) var presentToast
    
    @StateObject var viewModel = PhoneBindViewModel()
    @State private var phone:String = ""
    @State private var captcha:String = ""
    @State private var captchaReSend:String = ""
    @State private var countDown = 60
    // 手机号确认
    @State var showConfirmPhone:Bool = false
    // 显示验证码
    @State var showCaptchaView:Bool = false
    // 正在发送验证码，显示倒计时
    @State var isSendingCaptcha:Bool = false
    @State private var timer: Timer?
    @State private var timerActive: Bool = false
    
    var body: some View {
        VStack {
            TextField("请输入新手机号", text: $phone)
                .padding(EdgeInsets(top: 16, leading: 25, bottom: 16, trailing: 25))
                .background(Color.koiColorBackgroundItem)
                .cornerRadius(40)
                .keyboardType(.numberPad)
                .frame(width: 272)
                .onChange(of: phone) { value in
                    if value.count > maxPhoneLenght {
                        phone = String(value.prefix(maxPhoneLenght))
                    }
                }
                .padding(.top, 16)
                
            if showCaptchaView {
                ZStack {
                    TextField("输入验证码", text: $captcha)
                        .padding(EdgeInsets(top: 16, leading: 25, bottom: 16, trailing: 25))
                        .background(Color.koiColorBackgroundItem)
                        .cornerRadius(40)
                        .keyboardType(.numberPad)
                        .frame(width: 272)
                    
                    HStack {
                        Spacer()
                        if isSendingCaptcha {
                            Text(String(describing: countDown))
                                .font(.system(size: 13))
                                .foregroundColor(Color.koiColorTitle)
                                .padding(.trailing , 20)
                        } else {
                            Button(action: {
                                sendCaptcha(phone: phone)
                            }) {
                                Text(captchaReSend)
                                    .font(.system(size: 13))
                                    .foregroundColor(Color.koiColorPrimary)
                                    .padding(.trailing , 20)
                            }
                        }
                    }
                    .frame(width: 272)
                }
                .padding(.top, 10)
            }
            
            Button(action: {
                if showCaptchaView {
                    bindPhone(phone: phone, captcha: captcha)
                } else {
                    showConfirmPhone = true
                }
            }) {
                Text("确定")
                    .font(.system(size: 16))
                    .bold()
                    .padding(EdgeInsets(top: 16, leading: 0, bottom: 16, trailing: 0))
                    .frame(width: 272)
                    .foregroundColor(Color.white)
                    .background(Color.koiColorPrimary)
                    .cornerRadius(40)
                    .padding(.top, 20)
                    .alert("确认手机号", isPresented: $showConfirmPhone, actions: {
                        Button("取消", role: .cancel, action:{})
                        Button("确定", role: .cancel, action: {
                            sendCaptcha(phone: phone)
                        })
                    }, message: { Text("我们将发送验证码到这个号码：\(phone)")})
            }

            Spacer()
        }
        .modifier(KoiToolbarModifier(title: Text("绑定手机")))
        .onChange(of: viewModel.captchaState) { value in
            if value == "success" {
                viewModel.captchaState = ""
                showCaptchaView = true
                presentToast(.init(message: "验证码已发送"))
            }
        }
        .onChange(of: viewModel.bindState) { value in
            if value == "success" {
                viewModel.bindState = ""
                presentToast(.init(message: "绑定成功"))
                presentationMode.wrappedValue.dismiss()
            }
        }
    }
    
    private func sendCaptcha(phone: String) {
        if phone.isEmpty {
            presentToast(.init(message: "请输入手机号"))
            return
        }
        startTimer()
        viewModel.sendCaptcha(phone: phone)
    }
    
    private func bindPhone(phone: String, captcha: String) {
        viewModel.bindPhone(phone: phone, captcha: captcha)
    }
    
    private func startTimer() {
        isSendingCaptcha = true
        countDown = 60
        timerActive = true
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
            if countDown > 0 {
                countDown -= 1
            } else {
                timer?.invalidate()
                timerActive = false
                isSendingCaptcha = false
                captchaReSend = "重新发送"
            }
        }
    }
    
    func resetTimer() {
        timer?.invalidate()
        countDown = 60
        timerActive = false
    }
}

#Preview {
    PhoneBindNewView()
}
